import requests
import sys

from plugins.core.plugin import Plugin
from plugins.core.pluginvideo import PluginVideo
from plugins.core.pluginplaylist import PluginPlaylist

sys.path.append("..")
from src.vobjects.item import Item

from src.history import History

class AnilibriaRandom(Plugin):

    def __init__(self, history: History=History()):
        self.name = "AnilibriaTV: Random anime"
        self.is_query_required = False
        self.query_description = """"""
        self.history = history

        self.flag = "-alr"
        self.full_flag = "--anilibriarandom"
        self.flag_help = "show random anime"
        self.flag_action = "store_true"

        self.api_instance = "https://api.anilibria.tv/v2"
        self.instance = "https://anilibria.tv"

    def get_random(self):
        resp = requests.get(f"{self.api_instance}/getRandomTitle")

        if resp.status_code != 200: return list()
        resp = resp.json()

        items = []
        title = f"{resp['names']['ru']} ({resp['names']['en']})"
        host = "https://" + resp["player"]["host"]
        purl = f"{self.instance}/release/{resp['code']}.html"
        videos = list()

        for vid in resp["player"]["playlist"].values():
            ititle = "Episode " + str(vid["serie"])
            video = PluginVideo(
                title=ititle,
                playlist_title=title,
                url=host+vid["hls"]["hd"],
                length=resp["type"]["length"]
            )
            
            inHistory = video.in_history(self.history)
            item = video.to_item(inHistory=inHistory)
            item.fstr = f"{video.length} minutes"

            videos.append(item)

        playlist = PluginPlaylist(title, videos, url=purl)

        item = playlist.to_item()

        items.append(item)

        return items

    def get_items_by_query(self, query: str=""):
        return list()

    def get_items(self):
        return self.get_random()

if __name__ == "__main__":
    al = Anilibria()

    items = al.get_items_by_query(query="мастера меча онлайн")
    for item in items:
        print(item.title, item.parent.url)




